// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const db = uniCloud.database();
const dbCmd = db.command;
const dbGoods = db.collection('goods')
const dbCategories = db.collection('categories')
const dbGoodsRecord = db.collection('goods_record')
const dbInventoryRecords = db.collection('inventory_records')

//检查是否已经存在该物品
async function checkGoodsExistsAgain(event) {
	const {
		goods_id
	} = event;

	try {
		if (!goods_id) {
			return {
				exists: false,
				message: '物品编号不能为空'
			};
		}

		const res = await dbGoods.where({
			goods_id: goods_id
		}).count();

		return {
			exists: res.total > 0,
			total: res.total
		};
	} catch (error) {
		console.error('检查物品存在性失败:', error);
		return {
			exists: false,
			error: error.message
		};
	}
}

module.exports = {

	//新增分类
	async addCategories(event) {
		try {
			const res = await dbCategories.add(event);
			return {
				code: 0,
				message: '添加成功',
				data: res
			};
		} catch (e) {
			////console.error('添加失败:', e);
			return {
				code: e.code || -1,
				message: e.message || '添加失败',
				error: process.env.NODE_ENV === 'development' ? e : undefined
			};
		}
	},

	// 获取分类
	async getCategoriesList(event) {
		try {
			const {
				pageNum = 1,
				pageSize = 20,
				sortBy = 'sort', // 排序字段，默认 sort
				order = 'asc', // 排序方式，默认升序 asc / desc
				...query
			} = event;

			// ////console.log(query, '查询条件');

			// 构建基础查询：只查询正常状态的分类（status=0）
			let dbQuery = db.collection('categories').where({
				status: 0
			});

			// 应用其他查询条件
			if (query._id) {
				// 查询单个文档
				const res = await db.collection('categories').doc(query._id).get();
				return {
					code: 0,
					data: res.data || [], // 包装成数组统一格式
					message: 'success'
				};
			} else if (query.name) {
				// 模糊搜索 name
				dbQuery = dbQuery.where({
					name: new RegExp(query.name, 'i')
				});
			}

			// 添加排序逻辑
			if (sortBy) {
				dbQuery = dbQuery.orderBy(sortBy, order.toLowerCase() === 'desc' ? 'desc' : 'asc');
			}

			// 执行分页查询
			const res = await dbQuery
				.skip((pageNum - 1) * pageSize)
				.limit(pageSize)
				.get();

			return {
				code: 0,
				data: res.data,
				message: 'success'
			};
		} catch (error) {
			// ////console.error('分类列表查询异常:', error);
			return {
				code: 500,
				message: '查询失败: ' + (error.message || '未知错误')
			};
		}
	},

	// 更新分类
	async updateCategory(id, data) {
		try {
			// 参数校验
			if (!id) {
				return {
					code: -2,
					message: '缺少分类ID'
				};
			}

			if (!data || typeof data !== 'object' || Object.keys(data).length === 0) {
				return {
					code: -3,
					message: '更新数据不能为空'
				};
			}

			// 确保包含状态字段
			if (data.status === undefined) {
				data.status = 0; // 默认启用状态
			}

			// 执行更新
			const res = await dbCategories.doc(id).update(data);

			if (res.updated === 1) {
				return {
					code: 0,
					message: '更新成功'
				};
			} else {
				return {
					code: -1,
					message: '更新失败'
				};
			}
		} catch (error) {
			// ////console.error('更新分类异常:', error);
			return {
				code: 500,
				message: '服务器内部错误',
				error_detail: error.message
			};
		}
	},

	//根据id获取物品信息
	// 根据id获取物品信息
	async getGoodsById(event) {
		// 参数校验
		if (!event || !event._id) {
			return {
				code: -2,
				message: '缺少ID参数'
			};
		}

		try {
			// 查询数据库
			const res = await dbGoods.doc(event._id).get();

			// 检查查询结果
			if (!res.data || res.data.length === 0) {
				return {
					code: -3,
					message: '未找到对应商品',
					data: null
				};
			}

			// 返回查询结果
			return {
				code: 0,
				data: res.data[0], // doc.get()返回数组，取第一个元素
				message: '查询成功'
			};
		} catch (error) {
			// 错误处理
			console.error('商品查询失败:', error);
			return {
				code: -1,
				message: '数据库查询失败',
				error: error.message
			};
		}
	},

	// index.obj.js - 修改 getGoods 方法
	async getGoods(event) {
		const {
			queryCondition = {},
			pageNum = 1,
			pageSize = 10
		} = event;

		try {
			// 支持关键词模糊搜索（名称和编号）
			if (queryCondition.keyword) {
				const keyword = queryCondition.keyword;
				delete queryCondition.keyword;

				const regex = {
					$regex: keyword,
					$options: 'i'
				};

				queryCondition.$or = [{
						name: regex
					},
					{
						goods_id: regex
					}
				];
			}

			// 分页计算
			const skip = (pageNum - 1) * pageSize;

			// 同时获取数据和总数
			const [dataRes, countRes] = await Promise.all([
				dbGoods.where(queryCondition)
				.orderBy('add_date', 'asc') // 新增排序条件
				.skip(skip)
				.limit(pageSize)
				.get(),
				dbGoods.where(queryCondition).count()
			]);

			return {
				code: 0,
				message: '查询成功',
				data: dataRes.data,
				total: countRes.total
			};
		} catch (error) {
			console.error('物品信息查询异常:', error);
			return {
				code: 500,
				message: '服务器内部错误',
				error_detail: error.message
			};
		}
	},

	//检查是否已经存在该物品
	async checkGoodsExists(event) {
		const {
			goods_id
		} = event;

		try {
			if (!goods_id) {
				return {
					exists: false,
					message: '物品编号不能为空'
				};
			}

			const res = await dbGoods.where({
				goods_id: goods_id
			}).count();

			return {
				exists: res.total > 0,
				total: res.total
			};
		} catch (error) {
			console.error('检查物品存在性失败:', error);
			return {
				exists: false,
				error: error.message
			};
		}
	},

	//新增物品
	async addGoods(event) {
		try {
			// 新增：服务器端二次验证
			const checkRes = await checkGoodsExistsAgain({
				goods_id: event.goods_id
			});

			if (checkRes.exists) {
				return {
					code: 409, // 冲突状态码
					message: '物品编号已存在'
				};
			}

			// 添加商品
			const res = await dbGoods.add(event);
			
			if (res.id && event.remain_count > 0) {
				// 获取商品信息 for inventory record
				const goodsInfo = await dbGoods.doc(res.id).get();
				const goods = goodsInfo.data && goodsInfo.data.length > 0 ? goodsInfo.data[0] : null;
				
				if (goods) {
					// 获取分类信息
					let categoryName = '';
					if (goods.category_id) {
						try {
							const categoryRes = await db.collection('categories').doc(goods.category_id).get();
							if (categoryRes.data && categoryRes.data.length > 0) {
								categoryName = categoryRes.data[0].name;
							}
						} catch (e) {
							console.error('获取分类信息失败:', e);
						}
					}
					
					try {
						// 创建入库记录
						await dbInventoryRecords.add({
							goods_id: res.id,
							goods_name: goods.name,
							goods_category_id: goods.category_id,
							goods_category_name: categoryName,
							goods_brand: goods.brand,
							goods_model: goods.model,
							type: 1, // 入库
							change_count: event.remain_count,
							before_count: 0,
							after_count: event.remain_count,
							operator: event.operator || 'system',
							operator_name: event.operator_name || 'system',
							reason: '新增物品入库',
							create_date: Date.now()
						});
					} catch (inventoryError) {
						console.error('创建库存记录失败:', inventoryError);
						// 即使记录失败，也返回成功，因为主要商品已添加
					}
				}
			}
			
			return {
				code: 0,
				message: '添加成功',
				data: res
			};
		} catch (e) {
			////console.error('添加失败:', e);
			return {
				code: e.code || -1,
				message: e.message || '添加失败',
				error: process.env.NODE_ENV === 'development' ? e : undefined
			};
		}
	},

	//修改物品
	// 修改后的 updateGoods 方法
	async updateGoods(params) {
		try {
			// 参数校验
			if (!params?._id) {
				return {
					code: -2,
					message: '缺少物品ID参数'
				};
			}
			if (!params?.data || typeof params.data !== 'object' || Object.keys(params.data).length === 0) {
				return {
					code: -3,
					message: '更新数据不能为空且必须为对象格式'
				};
			}

			// 获取当前商品信息，用于记录库存变动
			const currentGoodsRes = await dbGoods.doc(params._id).get();
			const currentGoods = currentGoodsRes.data && currentGoodsRes.data.length > 0 ? currentGoodsRes.data[0] : null;
			
			if (!currentGoods) {
				return {
					code: -4,
					message: '商品不存在'
				};
			}

			const beforeCount = currentGoods.remain_count || 0;
			const newCount = params.data.remain_count !== undefined ? params.data.remain_count : currentGoods.remain_count;
			const changeCount = newCount - beforeCount;

			// 执行更新操作
			const updateResult = await dbGoods.doc(params._id).update(params.data);

			// 处理更新结果
			if (updateResult.updated === 0) {
				return {
					code: 1,
					message: '数据未发生变更',
					updatedId: params._id
				};
			}

			// 如果库存数量发生变化，创建库存变动记录
			if (changeCount !== 0) {
				try {
					// 获取商品信息 for inventory record
					const goodsInfo = await dbGoods.doc(params._id).get();
					const goods = goodsInfo.data && goodsInfo.data.length > 0 ? goodsInfo.data[0] : currentGoods;
					
					// 获取分类信息
					let categoryName = '';
					if (goods.category_id) {
						try {
							const categoryRes = await db.collection('categories').doc(goods.category_id).get();
							if (categoryRes.data && categoryRes.data.length > 0) {
								categoryName = categoryRes.data[0].name;
							}
						} catch (e) {
							console.error('获取分类信息失败:', e);
						}
					}
					
					// 确定操作类型：正数为入库，负数为出库
					const type = changeCount > 0 ? 1 : 2; // 1: 入库, 2: 出库
					const absChangeCount = Math.abs(changeCount);

					await dbInventoryRecords.add({
						goods_id: params._id,
						goods_name: goods.name,
						goods_category_id: goods.category_id,
						goods_category_name: categoryName,
						goods_brand: goods.brand,
						goods_model: goods.model,
						type: type,
						change_count: changeCount, // 保存实际变化值（正或负）
						before_count: beforeCount,
						after_count: newCount,
						operator: params.operator || 'system',
						operator_name: params.operator_name || 'system',
						reason: params.reason || '库存调整',
						create_date: Date.now()
					});
				} catch (inventoryError) {
					console.error('创建库存变动记录失败:', inventoryError);
					// 即使记录失败，也返回成功，因为主要更新已完成
				}
			}

			return {
				code: 0,
				message: '数据更新成功',
				updatedId: params._id,
				affected: updateResult.updated,
				timestamp: new Date().toISOString()
			};
		} catch (error) {
			// 关键修复：添加错误返回
			console.error('更新物品失败:', error);
			return {
				code: 500,
				message: '更新失败: ' + error.message
			};
		}
	},

	//根据分类id获取物品
	async getGoodsListByCategoriesId(event) {
		try {
			const res = await dbGoods
				.where(event)
				.orderBy('add_date', 'asc')
				.get();

			if (!res.data.length) {
				return {
					code: -1,
					message: '未找到相关数据'
				};
			}

			return {
				code: 0,
				message: '查询成功',
				data: res.data
			};
		} catch (error) {
			////console.error('物品分类信息查询异常:', error);
			return {
				code: 500,
				message: '服务器内部错误',
				error_detail: error.message
			};
		}
	},

	//联表查询
	async getCategoriesAndGoods() {
		const db = uniCloud.database()
		try {
			const res = await dbCategories
				.aggregate().project({
					_id: 1,
					name: 1,
					sort: 1,
					status: 1
				}).match({
					status: 0
				}).sort({
					sort: 1
				})
				.lookup({
					from: 'goods',
					localField: '_id',
					foreignField: 'category_id',
					as: 'goodsList'
				})
				.end()

			// 格式化返回数据
			return {
				code: 200,
				data: res.data.map(categories => ({
					_id: categories._id,
					name: categories.name,
					data: categories.goodsList.map(goods => ({
						_id: goods._id,
						category_id: goods.category_id,
						name: goods.name,
						remain_count: goods.remain_count,
						model: goods.model,
						brand: goods.brand,
						desc: goods.desc,
						thumb: goods.thumb
					}))
				})),
				message: 'success'
			}
		} catch (e) {
			return {
				code: 500,
				message: '查询失败: ' + e.message
			}
		}
	},
	async checkStockBeforeUpdate(event) {
		try {
			// 验证输入格式
			if (!Array.isArray(event)) {
				return {
					code: -2,
					message: '参数格式错误，需传递商品数组'
				};
			}

			// 检查库存是否充足
			const stockChecks = await Promise.all(
				event.map(item =>
					// [!code focus:2]
					// 修正：将 .field('remain_count') 修改为对象格式 .field({ remain_count: true })
					db.collection('goods').doc(item._id).field({
						remain_count: true
					}).get()
				)
			);

			const insufficientItems = [];
			event.forEach((item, index) => {
				// 健壮性检查：确保查询到了数据
				if (!stockChecks[index].data || stockChecks[index].data.length === 0) {
					throw new Error(`未能查询到商品 ${_id} 的库存信息。`);
				}

				const currentStock = stockChecks[index].data[0].remain_count;
				if (currentStock < item._cartNumber) {
					insufficientItems.push({
						_id: item._id,
						name: item.name,
						required: item._cartNumber,
						available: currentStock
					});
				}
			});

			if (insufficientItems.length > 0) {
				return {
					code: -5,
					message: '部分商品库存不足',
					insufficientItems
				};
			}

			return {
				code: 0,
				message: '库存充足'
			};
		} catch (error) {
			console.error('库存检查失败:', error); // 在控制台打印更详细的错误
			return {
				code: -1,
				message: '库存检查失败',
				error: error.message
			};
		}
	},
	//添加领用记录
	async addGoodsRecord(event) {
		try {
			let res = await dbGoodsRecord.add(event); // 确保参数正确
			return {
				code: 0,
				message: '添加成功',
				data: res
			};
		} catch (error) {
			////console.error('添加商品记录失败:', error); // 记录错误日志
			return { // 返回错误信息
				code: -1,
				message: '添加失败，请检查数据或稍后重试',
				// 可根据环境决定是否暴露error详情
				error: process.env.NODE_ENV === 'development' ? error.message : undefined
			};
		}
	},

	// 批量减少库存（适配前端传入的数组格式）
	// 批量减少库存（适配前端传入的数组格式）
	async batchUpdateGoods(event) {
		try {
			const normalizedEvent = Array.isArray(event) ?
				event.map(item => ({
					...item,
					_id: item._id + "",
					_cartNumber: Number(item._cartNumber)
				})) : [];

			if (!Array.isArray(normalizedEvent)) {
				return {
					code: -2,
					message: '参数格式错误，需传递商品数组'
				};
			}

			const invalidItems = normalizedEvent.filter(item =>
				!item._id || isNaN(item._cartNumber) || item._cartNumber <= 0
			);

			if (invalidItems.length > 0) {
				return {
					code: -3,
					message: `存在${invalidItems.length}条无效数据`,
					invalidItems
				};
			}

			const transaction = await db.startTransaction();

			try {
				// 通过 map 构建所有 update promise
				const updatePromises = normalizedEvent.map(async item => {
					// 获取商品信息 for inventory record
					const goodsInfo = await transaction.collection('goods').doc(item._id).get();
					const goods = goodsInfo.data && goodsInfo.data.length > 0 ? goodsInfo.data[0] : null;
					const beforeCount = goods ? goods.remain_count || 0 : 0;
					const afterCount = beforeCount - item._cartNumber;
					
					const res = await transaction.collection('goods')
						.doc(item._id)
						.update({
							remain_count: dbCmd.inc(-item._cartNumber)
						});

					// 创建出库记录
					if (goods) {
						// 获取分类信息
						let categoryName = '';
						if (goods.category_id) {
							try {
								const categoryRes = await transaction.collection('categories').doc(goods.category_id).get();
								if (categoryRes.data && categoryRes.data.length > 0) {
									categoryName = categoryRes.data[0].name;
								}
							} catch (e) {
								console.error('获取分类信息失败:', e);
							}
						}
						
						await transaction.collection('inventory_records').add({
							goods_id: item._id,
							goods_name: goods.name,
							goods_category_id: goods.category_id,
							goods_category_name: categoryName,
							goods_brand: goods.brand,
							goods_model: goods.model,
							type: 2, // 出库
							change_count: -item._cartNumber, // 负数表示出库
							before_count: beforeCount,
							after_count: afterCount,
							operator: 'system',
							operator_name: 'system',
							reason: '物品领用',
							create_date: Date.now()
						});
					}

					return {
						item,
						result: res
					};
				});

				const results = await Promise.all(updatePromises);
				const failedUpdates = results.filter(r => r.result.updated === 0);

				if (failedUpdates.length > 0) {
					await transaction.rollback();
					const failedNames = failedUpdates.map(r => r.item.name).join(', ');
					return {
						code: -4,
						message: `库存不足：[${failedNames}]，已回滚全部操作`,
						failedItems: failedUpdates.map(r => r.item)
					};
				}

				await transaction.commit();
				return {
					code: 0,
					message: `成功扣除库存 ${normalizedEvent.length} 种商品`
				};

			} catch (txError) {
				await transaction.rollback();
				console.error('批量更新事务失败:', txError);
				return {
					code: -1,
					message: '事务失败: ' + txError.message
				};
			}

		} catch (e) {
			console.error('前置操作失败:', e);
			return {
				code: -1,
				message: '前置验证异常',
				error: e.message
			};
		}
	},
	//根据id和模糊搜索
	async getGoodsRecordByUserId(event) {
		try {
			const {
				user_id,
				keyword
			} = event;
			////console.log("接收参数 user_id:", user_id, "keyword:", keyword);

			const db = uniCloud.database();
			const dbCmd = db.command;

			// 构建基础状态条件
			let statusCondition = {
				user_id: user_id
			};

			// 构建关键词条件
			let keywordCondition;
			if (keyword && typeof keyword === 'string' && keyword.trim() !== '') {
				const trimmedKeyword = keyword.trim();

				// 使用云函数兼容的模糊查询写法
				const fuzzySearch = {
					$regex: trimmedKeyword,
					$options: 'i'
				};

				keywordCondition = dbCmd.or({
						order_id: fuzzySearch
					}, // 精确匹配ID		
					{
						"goods.name": fuzzySearch
					} // 模糊匹配商品名
				);
			}

			// 组合最终查询条件
			const queryConditions = keyword ?
				dbCmd.and(statusCondition, keywordCondition) :
				statusCondition;

			////console.log("优化后查询条件:", JSON.stringify(queryConditions, null, 2));

			const res = await db.collection('goods_record')
				.where(queryConditions)
				.orderBy('create_date', 'desc')
				.get();

			return res.data?.length ? {
				code: 0,
				message: '查询成功',
				data: res.data
			} : {
				code: -1,
				message: '未找到相关数据'
			};
		} catch (error) {
			////console.error('查询异常:', error);
			return {
				code: 500,
				message: '服务器内部错误',
				error_detail: error.message
			};
		}
	},
	//根据id获取领用记录
	async getGoodsRecordById(queryParams) {
		try {
			// 参数校验
			if (!queryParams || Object.keys(queryParams).length === 0) {
				return {
					code: 400,
					data: null,
					message: '查询条件不能为空'
				}
			}

			// 添加查询超时设置
			const res = await dbGoodsRecord
				.where(queryParams)
				.limit(1) // 明确限制只取一条
				.get({
					timeout: 5000
				}) // 添加超时设置

			// 处理查询结果
			if (res.data && res.data.length > 0) {
				return {
					code: 0,
					data: res.data[0],
					message: '查询成功'
				}
			} else {
				return {
					code: 404,
					data: null,
					message: '未找到相关商品记录'
				}
			}
		} catch (error) {
			console.error('商品记录查询失败:', error)

			// 根据错误类型返回不同消息
			let errorMsg = '数据库查询异常'
			if (error.errCode === 'DATABASE_TIMEOUT') {
				errorMsg = '查询超时，请重试'
			} else if (error.errCode === 'DATABASE_PERMISSION_DENIED') {
				errorMsg = '无查询权限'
			}

			return {
				code: 500,
				data: null,
				message: errorMsg,
				errorDetail: process.env.NODE_ENV === 'development' ? error : undefined
			}
		}
	},
	//根据条件获取领用记录
	async getGoodsRecord(event) {
		try {
			const {
				user_id,
				status,
				keyword,
				page = 1, // 接收page参数
				pageSize = 10
			} = event;

			const db = uniCloud.database();
			const dbCmd = db.command;

			// 构建基础查询条件
			let queryConditions = {};

			// 状态条件处理
			if (status !== undefined) {
				queryConditions.status = status;
			}
			// 用户id条件处理
			if (user_id !== undefined) {
				queryConditions.user_id = user_id;
			}

			// 关键词条件处理（修正版）
			if (keyword && keyword.trim()) {
				const trimmedKeyword = keyword.trim();
				const fuzzySearch = {
					$regex: trimmedKeyword,
					$options: 'i'
				};
				// 修正条件组合方式
				queryConditions = dbCmd.and(queryConditions,
					dbCmd.or({
							order_id: fuzzySearch
						}, // 独立条件对象
						{
							user_name: fuzzySearch
						}, // 独立条件对象
						{
							"goods.name": fuzzySearch
						} // 正确嵌套字段查询
					)
				);
			}

			// 分页计算
			const skip = (page - 1) * pageSize;

			// 分页查询
			const query = db.collection('goods_record')
				.where(queryConditions)
				.orderBy('create_date', 'desc')
				.skip(skip)
				.limit(pageSize);

			// 获取数据和总数
			const [dataRes, countRes] = await Promise.all([
				query.get(),
				db.collection('goods_record').where(queryConditions).count()
			]);

			return {
				code: 0,
				data: dataRes.data,
				total: countRes.total,
				message: 'success'
			};
		} catch (error) {
			//console.error('查询异常:', error);
			return {
				code: 500,
				message: '服务器内部错误',
				error_detail: error.message
			};
		}
	},
	//根据条件获取归还中的领用记录
	async getGoodsRecordReturn(event) {
		try {
			const {
				status,
				keyword,
				page = 1, // 接收page参数
				pageSize = 10
			} = event;

			const db = uniCloud.database();
			const dbCmd = db.command;

			// 构建基础查询条件
			let queryConditions = {
				status: 1,
				"goods.status": status
			};

			//console.log(queryConditions,'queryConditions')

			// 关键词条件处理（修正版）
			if (keyword && keyword.trim()) {
				const trimmedKeyword = keyword.trim();
				const fuzzySearch = {
					$regex: trimmedKeyword,
					$options: 'i'
				};
				// 修正条件组合方式
				queryConditions = dbCmd.and(queryConditions,
					dbCmd.or({
							order_id: fuzzySearch
						}, // 独立条件对象
						{
							user_name: fuzzySearch
						}, // 独立条件对象
						{
							"goods.name": fuzzySearch
						} // 正确嵌套字段查询
					)
				);
			}

			// 分页计算
			const skip = (page - 1) * pageSize;

			// 分页查询
			const query = db.collection('goods_record')
				.where(queryConditions)
				.orderBy('create_date', 'desc')
				.skip(skip)
				.limit(pageSize);

			// 获取数据和总数
			const [dataRes, countRes] = await Promise.all([
				query.get(),
				db.collection('goods_record').where(queryConditions).count()
			]);

			return {
				code: 0,
				data: dataRes.data,
				total: countRes.total,
				message: 'success'
			};
		} catch (error) {
			//console.error('查询异常:', error);
			return {
				code: 500,
				message: '服务器内部错误',
				error_detail: error.message
			};
		}
	},
	//修改领用记录状态
	async updateRecordStatus(event) {
		try {
			// ==================== 参数校验 ====================
			console.log('updateRecordStatus called with event:', JSON.stringify(event)); // 添加日志
			
			if (!event?._id) {
				return {
					code: -2,
					message: '缺少领用记录ID'
				};
			}
			if (event.status === undefined || typeof event.status !== 'number') {
				return {
					code: -3,
					message: '状态值不合法'
				};
			}
			
			// Validate that we have the necessary goods data
			if (!event.data) {
				return {
					code: -4,
					message: '缺少商品数据'
				};
			}
			
			// Extract goods information
			const goodsId = event.data._id;
			const cartNumber = event.data._cartNumber;
			
			if (!goodsId || cartNumber === undefined) {
				console.error('Missing goods ID or cart number. Event data:', event.data);
				return {
					code: -5,
					message: '商品数据不完整: 缺少物品ID或数量'
				};
			}

			const transaction = await db.startTransaction();
			try {
				// ==================== 1.更新领用记录状态 ====================
				const recordUpdate = await transaction
					.collection('goods_record')
					.doc(event._id)
					.update({
						status: event.status,
						approve_name: event.approve_name,
						approve_date: event.approve_date,
						refuse: event.refuse,
						note: event.note
					});

				console.log('Updated record status to:', event.status); // 添加日志

				// 根据状态操作库存和记录
				// 状态 0: 待核准
				// 状态 1: 已核准 (同意领用，库存减少，创建出库记录) - THIS CREATES OUT RECORD
				// 状态 2: 已驳回 (库存返还，不创建记录) 
				// 状态 3: 已取消 (库存返还，不创建记录)
				if (event.status === 1) { // 同意领用，库存减少（出库）
					console.log('Processing approval for goods ID:', goodsId, 'quantity:', cartNumber); // 添加日志
					
					// 获取商品信息 for inventory record
					// First check if we already have the goods data in the event
					let goods = null;
					if (event.data && event.data.name) {
						// Goods data is already provided in the event
						goods = event.data;
						console.log('Using goods data from event:', goods.name); // 添加日志
					} else {
						// Need to fetch goods data from database
						const goodsDoc = await transaction.collection('goods').doc(goodsId).get();
						goods = goodsDoc.data && goodsDoc.data.length > 0 ? goodsDoc.data[0] : null;
						console.log('Fetched goods data from database:', goods ? goods.name : 'not found'); // 添加日志
					}
					
					if (goods) {
						console.log('Found goods info:', goods.name, 'current count:', goods.remain_count); // 添加日志
						const beforeCount = goods.remain_count || 0;
						const afterCount = beforeCount - cartNumber;
						// 执行库存减少操作
						const stockResult = await transaction
							.collection('goods')
							.doc(goodsId)
							.update({
								remain_count: dbCmd.inc(-cartNumber)
							});
							
						console.log('Stock update result:', stockResult); // 添加日志
						
						// 检查库存更新是否成功
						if (stockResult.updated === 0) {
							throw new Error('库存更新失败');
						}
							
						// 获取分类信息
						let categoryName = '';
						if (goods.category_id) {
							try {
								const categoryRes = await transaction.collection('categories').doc(goods.category_id).get();
								if (categoryRes.data && categoryRes.data.length > 0) {
									categoryName = categoryRes.data[0].name;
								}
							} catch (e) {
								console.error('获取分类信息失败:', e);
							}
						}
						
						// 创建出库记录 (only for approval)
						const inventoryRecord = await transaction.collection('inventory_records').add({
							goods_id: goodsId,
							goods_name: goods.name,
							goods_category_id: goods.category_id,
							goods_category_name: categoryName,
							goods_brand: goods.brand,
							goods_model: goods.model,
							type: 2, // 出库
							change_count: -cartNumber, // 负数表示出库
							before_count: beforeCount,
							after_count: afterCount,
							operator: event.operator || 'system',
							operator_name: event.operator_name || 'system',
							reason: '物品领用',
							create_date: Date.now()
						});
						console.log('Created inventory record with ID:', inventoryRecord.id); // 添加日志
					} else {
						console.log('Could not find goods with ID:', goodsId); // 添加日志
						throw new Error('找不到指定的商品信息');
					}
				} else if (event.status === 2 || event.status === 3) { // 拒绝或取消，库存返还（不创建入库记录，因为物品还没真正借出）
					console.log('Processing rejection/cancellation for goods ID:', goodsId); // 添加日志
					
					// 获取商品信息 for inventory record
					let goods = null;
					if (event.data && event.data.name) {
						// Goods data is already provided in the event
						goods = event.data;
						console.log('Using goods data from event for rejection:', goods.name); // 添加日志
					} else {
						// Need to fetch goods data from database
						const goodsDoc = await transaction.collection('goods').doc(goodsId).get();
						goods = goodsDoc.data && goodsDoc.data.length > 0 ? goodsDoc.data[0] : null;
						console.log('Fetched goods data from database for rejection:', goods ? goods.name : 'not found'); // 添加日志
					}
					
					if (goods) {
						// 对于拒绝或取消的情况，只更新库存，但不创建入库记录
						// 因为物品还没有真正借出，所以不需要入库记录
						const stockResult = await transaction
							.collection('goods')
							.doc(goodsId)
							.update({
								remain_count: dbCmd.inc(cartNumber)
							});
							
						// 检查库存更新是否成功
						if (stockResult.updated === 0) {
							throw new Error('库存返还失败');
						}
					}
				}

				// ==================== 提交事务 ====================
				await transaction.commit();
				console.log('Transaction committed successfully'); // 添加日志

				return {
					code: 0,
					message: '操作成功',
					data: {
						record: {
							id: event._id,
							newStatus: event.status
						}
					}
				};
			} catch (txError) {
				console.error('Transaction error:', txError); // 添加错误日志
				// ==================== 事务回滚 ====================
				await transaction.rollback();
				return {
					code: 500,
					message: '操作失败: ' + txError.message,
					detail: process.env.NODE_ENV === 'development' ? {
						stack: txError.stack
					} : undefined
				};
			}
		} catch (error) {
			console.error('Global error in updateRecordStatus:', error); // 添加错误日志
			return {
				code: 500,
				message: '服务器内部错误',
				error: process.env.NODE_ENV === 'development' ? error.message : undefined
			};
		}
	},

	//修改领用物品记录状态
	async updateGoodsRecordGoodsStatus(event) {
		try {
			// 参数校验
			if (!event?._id) {
				return {
					code: -2,
					message: '缺少领用记录ID参数'
				};
			}
			if (!event?.data || typeof event.data !== 'object' || Object.keys(event.data).length === 0) {
				return {
					code: -3,
					message: '更新数据不能为空且必须为对象格式'
				};
			}

			// 执行更新操作

			const updateResult = await dbGoodsRecord.where({
				'_id': event._id,
				'goods._id': event.data._id
			}).update({
				'goods.status': event.data.status
			})

			// 处理更新结果
			if (updateResult.updated === 0) { // 根据实际数据库驱动调整字段
				return {
					code: 1,
					message: '数据未发生变更',
					updatedId: event._id
				};
			}

			//更新库存数量
			if (event.data.status === 1) { // 归还商品，库存增加（入库）
				// 获取当前商品信息，用于记录库存变动前的数量
				const goodsRes = await dbGoods.doc(event.data._id).get();
				const currentGoods = goodsRes.data && goodsRes.data.length > 0 ? goodsRes.data[0] : null;
				
				if (currentGoods) {
					const beforeCount = currentGoods.remain_count || 0;
					const afterCount = beforeCount + event.data._cartNumber;
					
					//归还时，库存数量增加对应值
					const res = await dbGoods.doc(event.data._id).update({
						remain_count: dbCmd.inc(event.data._cartNumber)
					})
					
					// 处理更新结果
					if (res.updated === 0) { // 根据实际数据库驱动调整字段
						//回滚之前更新的状态
						const r = await dbGoodsRecord.where({
							'_id': event._id,
							'goods._id': event.data._id
						}).update({
							'goods.$.status': 0
						})
						return {
							code: 1,
							message: '数据更新出错，已回滚',
							updatedId: event._id
						};
					}
					
					// 获取分类信息
					let categoryName = '';
					if (currentGoods.category_id) {
						try {
							const categoryRes = await db.collection('categories').doc(currentGoods.category_id).get();
							if (categoryRes.data && categoryRes.data.length > 0) {
								categoryName = categoryRes.data[0].name;
							}
						} catch (e) {
							console.error('获取分类信息失败:', e);
						}
					}
					
					try {
						// 创建入库记录
						await dbInventoryRecords.add({
							goods_id: event.data._id,
							goods_name: currentGoods.name,
							goods_category_id: currentGoods.category_id,
							goods_category_name: categoryName,
							goods_brand: currentGoods.brand,
							goods_model: currentGoods.model,
							type: 1, // 入库
							change_count: event.data._cartNumber,
							before_count: beforeCount,
							after_count: afterCount,
							operator: event.operator || 'system',
							operator_name: event.operator_name || 'system',
							reason: '物品归还',
							create_date: Date.now()
						});
					} catch (inventoryError) {
						console.error('创建入库记录失败:', inventoryError);
						// 即使记录失败，也返回成功，因为主要操作已完成
					}
				}
			}
			return {
				code: 0,
				message: '数据更新成功',
				updatedId: event._id,
				affected: updateResult.updated, // 实际更新的文档数量
				timestamp: new Date().toISOString() // 添加操作时间戳
			};
		} catch (error) {
			////console.error('更新异常:', error.message);

			// 错误分类处理
			const errorInfo = {
				code: -1,
				message: '更新操作失败',
				detail: process.env.NODE_ENV === 'development' ? {
					error: error.message,
					stack: error.stack
				} : undefined
			};

			// 特定错误类型识别
			if (error.message.includes('DocumentNotFound')) {
				errorInfo.code = -4;
				errorInfo.message = '指定记录不存在';
			} else if (error.message.includes('InvalidData')) {
				errorInfo.code = -5;
				errorInfo.message = '提交数据格式非法';
			}

			return errorInfo;
		}
	},

	// 新增物品时添加入库记录
	async addGoodsWithInventoryRecord(event) {
		try {
			// 新增：服务器端二次验证
			const checkRes = await checkGoodsExistsAgain({
				goods_id: event.goods_id
			});

			if (checkRes.exists) {
				return {
					code: 409, // 冲突状态码
					message: '物品编号已存在'
				};
			}

			// 添加入库记录
			if (event.remain_count > 0) {
				// 先添加商品
				const res = await dbGoods.add(event);
				
				if (res.id) {
					const goodsInfo = await dbGoods.doc(res.id).get();
					const goods = goodsInfo.data && goodsInfo.data.length > 0 ? goodsInfo.data[0] : null;
					
					if (goods) {
						// 获取分类信息
						let categoryName = '';
						if (goods.category_id) {
							try {
								const categoryRes = await db.collection('categories').doc(goods.category_id).get();
								if (categoryRes.data && categoryRes.data.length > 0) {
									categoryName = categoryRes.data[0].name;
								}
							} catch (e) {
								console.error('获取分类信息失败:', e);
							}
						}
						
						// 创建入库记录
						await dbInventoryRecords.add({
							goods_id: res.id,
							goods_name: goods.name,
							goods_category_id: goods.category_id,
							goods_category_name: categoryName,
							goods_brand: goods.brand,
							goods_model: goods.model,
							type: 1, // 入库
							change_count: event.remain_count,
							before_count: 0,
							after_count: event.remain_count,
							operator: event.operator || 'system',
							operator_name: event.operator_name || 'system',
							reason: '新增物品入库',
							create_date: Date.now()
						});
					}
				}

				return {
					code: 0,
					message: '添加成功',
					data: res
				};
			} else {
				// 如果初始库存为0，仍然添加商品但不创建库存记录
				const res = await dbGoods.add(event);
				return {
					code: 0,
					message: '添加成功',
					data: res
				};
			}
		} catch (e) {
			////console.error('添加失败:', e);
			return {
				code: e.code || -1,
				message: e.message || '添加失败',
				error: process.env.NODE_ENV === 'development' ? e : undefined
			};
		}
	},

	// 修改物品时添加库存变动记录
	async updateGoodsWithInventoryRecord(params) {
		try {
			// 参数校验
			if (!params?._id) {
				return {
					code: -2,
					message: '缺少物品ID参数'
				};
			}
			if (!params?.data || typeof params.data !== 'object' || Object.keys(params.data).length === 0) {
				return {
					code: -3,
					message: '更新数据不能为空且必须为对象格式'
				};
			}

			// 获取当前商品信息，用于记录库存变动
			const currentGoodsRes = await dbGoods.doc(params._id).get();
			const currentGoods = currentGoodsRes.data && currentGoodsRes.data.length > 0 ? currentGoodsRes.data[0] : null;
			
			if (!currentGoods) {
				return {
					code: -4,
					message: '商品不存在'
				};
			}

			const beforeCount = currentGoods.remain_count || 0;
			const newCount = params.data.remain_count !== undefined ? params.data.remain_count : currentGoods.remain_count;
			const changeCount = newCount - beforeCount;

			// 执行更新操作
			const updateResult = await dbGoods.doc(params._id).update(params.data);

			// 处理更新结果
			if (updateResult.updated === 0) {
				return {
					code: 1,
					message: '数据未发生变更',
					updatedId: params._id
				};
			}

			// 如果库存数量发生变化，创建库存变动记录
			if (changeCount !== 0) {
				const goodsInfo = await dbGoods.doc(params._id).get();
				const goods = goodsInfo.data && goodsInfo.data.length > 0 ? goodsInfo.data[0] : currentGoods;
				
				// 获取分类信息
				let categoryName = '';
				if (goods.category_id) {
					try {
						const categoryRes = await db.collection('categories').doc(goods.category_id).get();
						if (categoryRes.data && categoryRes.data.length > 0) {
							categoryName = categoryRes.data[0].name;
						}
					} catch (e) {
						console.error('获取分类信息失败:', e);
					}
				}
				
				// 确定操作类型：正数为入库，负数为出库
				const type = changeCount > 0 ? 1 : 2; // 1: 入库, 2: 出库
				const absChangeCount = Math.abs(changeCount);

				await dbInventoryRecords.add({
					goods_id: params._id,
					goods_name: goods.name,
					goods_category_id: goods.category_id,
					goods_category_name: categoryName,
					goods_brand: goods.brand,
					goods_model: goods.model,
					type: type,
					change_count: changeCount, // 保存实际变化值（正或负）
					before_count: beforeCount,
					after_count: newCount,
					operator: params.operator || 'system',
					operator_name: params.operator_name || 'system',
					reason: params.reason || '库存调整',
					create_date: Date.now()
				});
			}

			return {
				code: 0,
				message: '数据更新成功',
				updatedId: params._id,
				affected: updateResult.updated,
				timestamp: new Date().toISOString()
			};
		} catch (error) {
			// 关键修复：添加错误返回
			console.error('更新物品失败:', error);
			return {
				code: 500,
				message: '更新失败: ' + error.message
			};
		}
	},

	// 获取物品的库存变动记录
	async getInventoryRecords(params) {
		try {
			const {
				goods_id,
				type,
				operator,
				startDate,
				endDate,
				pageNum = 1,
				pageSize = 10
			} = params;

			let query = {};

			// 构建查询条件
			if (goods_id) {
				query.goods_id = goods_id;
			}
			if (type !== null && type !== undefined) {
				query.type = type;
			}
			if (operator) {
				query.operator = operator;
			}
			if (startDate || endDate) {
				query.create_date = {};
				if (startDate) {
					query.create_date.$gte = new Date(startDate).getTime();
				}
				if (endDate) {
					query.create_date.$lte = new Date(endDate).getTime();
				}
			}

			// 计算分页
			const skip = (pageNum - 1) * pageSize;

			// 并行查询数据和总数
			const [dataRes, countRes] = await Promise.all([
				dbInventoryRecords.where(query)
					.orderBy('create_date', 'desc')
					.skip(skip)
					.limit(pageSize)
					.get(),
				dbInventoryRecords.where(query).count()
			]);

			return {
				code: 0,
				message: '查询成功',
				data: dataRes.data,
				total: countRes.total,
				pageNum: pageNum,
				pageSize: pageSize
			};
		} catch (error) {
			console.error('查询库存记录失败:', error);
			return {
				code: 500,
				message: '查询失败: ' + error.message
			};
		}
	},

	// 根据物品ID获取库存变动记录
	async getInventoryRecordsByGoodsId(event) {
		try {
			if (!event.goods_id) {
				return {
					code: -2,
					message: '缺少物品ID参数'
				};
			}

			const records = await dbInventoryRecords
				.where({ goods_id: event.goods_id })
				.orderBy('create_date', 'desc')
				.get();

			return {
				code: 0,
				message: '查询成功',
				data: records.data
			};
		} catch (error) {
			console.error('查询物品库存记录失败:', error);
			return {
				code: 500,
				message: '查询失败: ' + error.message
			};
		}
	},

	_before: function() { // 通用预处理器

	}
}